package com.neo.controller;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.HttpURLConnection;

@RestController
@RequestMapping("/qiniu")
public class QiniuController {

    // 七牛云的密钥配置
    private static final String ACCESS_KEY = "fJ5f_vOXJJbFHnZkvAlizfJF3lhrDwCPxNyTnK9N";
    private static final String SECRET_KEY = "NdZnFEUxuSd-e463oUokwhqOzOhDJy44F2dX11rj";
    private static final String BUCKET = "longzhucloudrepo";
    private static final String DOMAIN = "your-bucket-domain";

    /**
     * 获取上传凭证
     */
    @GetMapping("/token")
    public String getUploadToken() {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth.uploadToken(BUCKET);
    }

    /**
     * 上传文件到七牛云
     */
    @PostMapping("/upload")
    public JSONObject uploadFile(@RequestParam("file") MultipartFile file) {
        JSONObject result = new JSONObject();
        if (file.isEmpty()) {
            result.put("code", 400);
            result.put("msg", "上传文件不能为空");
            return result;
        }

        try {
            // 构造一个带指定Region对象的配置类
            Configuration cfg = new Configuration(Region.huanan());
            UploadManager uploadManager = new UploadManager(cfg);

            // 获取文件的字节数组
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(BUCKET);

            // 上传文件
            Response response = uploadManager.put(uploadBytes, file.getOriginalFilename(), upToken);
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);

            result.put("code", 200);
            result.put("msg", "上传成功");
            result.put("data", putRet);
        } catch (QiniuException ex) {
            result.put("code", 500);
            result.put("msg", "上传失败：" + ex.response.toString());
        } catch (IOException ex) {
            result.put("code", 500);
            result.put("msg", "文件读取失败");
        }
        return result;
    }

    /**
     * 获取私有空间文件的下载地址
     */
    @GetMapping("/download/{fileName}")
    public JSONObject getDownloadUrl(@PathVariable String fileName) {
        JSONObject result = new JSONObject();
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        
        // 私有空间文件下载链接
        String publicUrl = String.format("%s/%s", DOMAIN, fileName);
        // 生成下载链接，有效期为3600秒
        String downloadUrl = auth.privateDownloadUrl(publicUrl, 3600);

        result.put("code", 200);
        result.put("msg", "获取下载链接成功");
        result.put("data", downloadUrl);
        return result;
    }

    /**
     * 下载文件到resources目录
     */
    @GetMapping("/download/local/{fileName}")
    public JSONObject downloadToLocal(@PathVariable String fileName) {
        JSONObject result = new JSONObject();
        String resourcePath = "src/main/resources/downloads/";
        File dir = new File(resourcePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String publicUrl = String.format("%s/%s", DOMAIN, fileName);
            String downloadUrl = auth.privateDownloadUrl(publicUrl, 3600);

            // 创建URL连接
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

            // 获取输入流
            try (InputStream inputStream = conn.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(resourcePath + fileName)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            result.put("code", 200);
            result.put("msg", "文件下载成功");
            result.put("data", resourcePath + fileName);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "下载失败：" + e.getMessage());
        }
        return result;
    }
}